import localCache from '@/utils/cache';
import { loadBMap } from '@/utils/map';
import { Toast } from 'vant';
import { cityjosn } from '@/utils/city.js';

const cityModule = {
  namespaced: true,
  state() {
    return {
      cityjosn,
      point: {
        province: '',
        city: '',
        latitude: '',
        longitude: ''
      }
    };
  },
  getters: {},
  mutations: {
    changePoint(state, point) {
      state.point.province = point.province;
      state.point.city = point.city;
      state.point.latitude = point.latitude;
      state.point.longitude = point.longitude;
    }
  },
  actions: {
    getArea({ commit }) {
      const that = this;
      // 定义回调函数
      window.initBaiduMapScript = () => {
        that.BMap = window.BMap;
        var geolocation = new that.BMap.Geolocation();
        geolocation.getCurrentPosition(
          function(r) {
            if (this.getStatus() == 0) {
              // 成功获取位置信息
              commit('changePoint', {
                province: r.address.province,
                city: r.address.city,
                latitude: r.latitude,
                longitude: r.longitude
              });
              localCache.setCache('point', {
                province: r.address.province,
                city: r.address.city,
                latitude: r.latitude,
                longitude: r.longitude
              });
            } else {
              // 无法获取到位置信息
              Toast('无法获取到位置信息!');
            }
          },
          {
            enableHighAccuracy: true
          }
        );
      };
      // 调用脚本获取位置信息
      loadBMap('initBaiduMapScript');
    }
  }
};

export default cityModule;
